<?php

include_once '_database_env.php';

function exec_sql($sql) {
  $con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWD, DB_NAME, DB_PORT);
  if ($con->connect_error) {
    // echo "连接失败: " . $con->connect_error;
    return false;
  }
  $con->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1);
  $result = $con->query($sql);
  if ($result && is_bool($result)) {
    return $result;
  } elseif ($result) {
    // 输出数据
    if ($result->num_rows > 0) {
      $output = [];
      while ($row = $result->fetch_assoc()) {
        array_push($output, $row);
      }
      return $output;
    }
  } else {
    return false;
  }
  $con->close();
}

function exec_sql_array($sql_arr) {
  $con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWD, DB_NAME, DB_PORT);
  if ($con->connect_error) {
    return [];
  }
  $con->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1);
  $results = [];
  foreach ($sql_arr as $sql) {
    $result = $con->query($sql . ';');
    if ($result && is_bool($result)) {
      array_push($results, $result);
    } elseif ($result) {
      // 输出数据
      if ($result->num_rows > 0) {
        $output = [];
        while ($row = $result->fetch_assoc()) {
          array_push($output, $row);
        }
        array_push($results, $output);
      }
    } else {
      array_push($results, false);
    }
  }
  return $results;
}

function escape_string($str) {
  $con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWD, DB_NAME, DB_PORT);
  $string = mysqli_real_escape_string($con, $str);
  $con->close();
  return $string;
}